/**
 * Created by XianTao on 2015/3/13
 *
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package com.taotao.game;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.domain.PlayGame;
import com.taotao.rop.response.BaseResponse;
import com.taotao.rop.util.DateTimeUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;

public abstract class ChanceGameController {
    protected abstract Object[][] getPrizeArray();
    protected abstract String msgWrongParameter();
    protected abstract int maxWechatCount();
    protected abstract int maxWechatMemberCount();
    protected abstract String msgAlreadyMemberJoin();
    protected abstract String msgAlreadyJoin();
    protected abstract int maxTelCount();
    protected abstract int maxTelMemberCount();
    protected abstract String msgOverMaxTelCount();

    /**游戏结束时调用的restful*/
    public abstract Object gameEnd(HttpServletRequest request, HttpServletResponse resp) throws UnsupportedEncodingException;

    /**获取中奖记录时调用的restful*/
    public abstract Object getMyPrizes(HttpServletRequest request, HttpServletResponse resp) throws UnsupportedEncodingException;


    /**获取中奖记录*/
    protected Object getPrizes(String appId, String openId, String gameName) {
        PlayGame condition = new PlayGame();
        condition.setGameName(gameName);
        condition.setAppId(appId);
        condition.setOpenId(openId);

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getMyPrizes", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                return respData;
            } else {
                return baseResponse;
            }
        }
        return response.getErrorResponse();
    }

    /**
     * 角度随机，i:最小角度的下标， j:最大角度的下标， awardIndex:随机中奖项的下标
     */
    protected Integer randomAngle(Object[][] prizeArr, int i, int j, int awardIndex) {
        int min = (Integer)prizeArr[awardIndex][i];
        int max = (Integer)prizeArr[awardIndex][j];
        return new Random().nextInt(max) % (max - min + 1) + min;
    }

    /**
     * 根据概率获取中奖项的下标，rateIndex:中奖概率的下标
     */
    protected Integer getAwardIndex(Object[][] prizeArr, int rateIndex) {
        //概率数组
        Integer obj[] = new Integer[prizeArr.length];
        for (int i = 0; i < prizeArr.length; i++) {
            obj[i] = (Integer) prizeArr[i][rateIndex];
        }

        //默认未中奖
        Integer result = prizeArr.length - 1;
        try {
            int sum = 0;//概率数组的总概率精度
            for (Integer anObj : obj) {
                sum += anObj;
            }
            for (int i = 0; i < obj.length; i++) {//概率数组循环
                int randomNum = new Random().nextInt(sum);//随机生成1到sum的整数
                if (randomNum < obj[i]) {//中奖
                    result = i;
                    break;
                } else {
                    sum -= obj[i];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    protected boolean endGame(String appId, String openId, String gameName, String tel, String result, String grade) {
        PlayGame condition = new PlayGame();
        condition.setAppId(appId);
        condition.setOpenId(openId);
        condition.setGameName(gameName);
        Date now = new Date();
        condition.setStartTime(DateTimeUtil.getDateStartMillis(now));
        condition.setEndTime(DateTimeUtil.getDateEndMillis(now));

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                try {
                    PlayGame playGame = new PlayGame();
                    playGame.setResult(result);
                    playGame.setPrize(Integer.parseInt(grade));
                    playGame.setTel(tel);
                    playGame.setFinishTime(DateTimeUtil.getDateMillis(new Date()));
                    if (respData != null && respData.size() > 0) {
                        if (respData.get(0).get("finishTime") != null) {
                            //会员次数；新增一条游戏记录
                            playGame.setAppId(appId);
                            playGame.setOpenId(openId);
                            playGame.setGameName(gameName);
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(playGame, BaseResponse.class, "playGame.insert", "1.0");
                            return true;
                        } else {
                            //更新游戏的后半段
                            Long id = Long.parseLong(respData.get(0).get("id").toString());
                            playGame.setId(id);
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(playGame, BaseResponse.class, "playGame.end", "1.0");
                            return true;
                        }
                    } else {
                        //新增一条游戏记录
                        playGame.setAppId(appId);
                        playGame.setOpenId(openId);
                        playGame.setGameName(gameName);
                        MyRopClient.getRopClient("").buildClientRequest()
                                .post(playGame, BaseResponse.class, "playGame.insert", "1.0");
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }
}
